package org.example.demo3.controller;

import org.example.demo3.entity.User;
import org.example.demo3.service.UserService;
import org.example.demo3.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;
import jakarta.servlet.http.HttpSession;

@Controller
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/login")
    public String loginPage() {
        return "user/login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam("username") String username, 
                       @RequestParam("password") String password,
                       HttpSession session,
                       Model model) {
        String md5Password = MD5Util.encode(password);
        User user = userService.login(username, md5Password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/survey/list";
        }
        model.addAttribute("error", "用户名或密码错误");
        return "user/login";
    }
    
    @GetMapping("/register")
    public String registerPage() {
        return "user/register";
    }
    
    @PostMapping("/register")
    public String register(User user, Model model) {
        try {
            user.setRole(0); // 设置为普通用户
            user.setPassword(MD5Util.encode(user.getPassword()));
            if (userService.register(user)) {
                return "redirect:/login?success=true";
            }
            model.addAttribute("error", "注册失败，用户名可能已存在");
            return "user/register";
        } catch (Exception e) {
            model.addAttribute("error", "系统错误：" + e.getMessage());
            return "user/register";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
    
    @ExceptionHandler(Exception.class)
    public String handleError(Exception e, Model model) {
        model.addAttribute("error", e.getMessage());
        return "error";
    }
}
